package com.juno.cafenoa;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.juno.cafenoa.member.LoginActivity;
import com.juno.cafenoa.net.AsyncTaskCompleteListener;
import com.juno.cafenoa.net.HttpPostTask;
import com.juno.cafenoa.sqlite.CafeNoaDBAdapter;
import com.juno.cafenoa.util.CafeNoaPreference;
import com.juno.cafenoa.util.Util;

/**
 * intro 화면. 어플 최초구동시 카페 마크와 함께 IN.
 * 2초(2000ms) 이후 activity 전환
 * 
 * @author JUNHO
 *
 */
public class IntroActivity extends Activity implements Runnable, Callback {
	Handler mHandler;
	Thread thread;
	Context mContext;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_intro);
		mContext = this;
		mHandler = new Handler(this);
		final String regId = GCMRegistrar.getRegistrationId(this);
		//등록된 ID가 없으면 ID값을 얻어옵니다
		if (regId.equals("") || regId == null) {
			GCMRegistrar.checkDevice(mContext);
			GCMRegistrar.checkManifest(mContext);
			Log.d("GCM", "GCM 정보 없음");
			GCMRegistrar.register(this, GCMIntentService.PROJECT_ID);

			String deviceToken = GCMRegistrar.getRegistrationId(mContext);
			Log.d("GCM", "deviceToken = "+deviceToken);
			if(!deviceToken.equalsIgnoreCase("")){
				GCMRegistrar.setRegisteredOnServer(mContext, true);
			}
		}else{
			Log.v("GCM", "Already Registered : " + regId);
			CafeNoaPreference.setGcmID(mContext, regId);
		}
		
		thread = new Thread(this);
		
		thread.start();
	}

	public void run() {
		// TODO Auto-generated method stub

		Message msg = Message.obtain(mHandler, 1000, 0, 0);
		mHandler.sendMessage(msg);

		try {
			Thread.sleep(2000);
			mHandler.sendEmptyMessage(0);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		msg = Message.obtain(mHandler, 2000, 0, 0);
		mHandler.sendMessage(msg);
	}

	public boolean handleMessage(Message msg) {
		// TODO Auto-generated method stub
		switch (msg.what) {
		case 2000: {
			// 패스워드가 있다면
			
			boolean userRegist = CafeNoaPreference.getRegistState(this);
			if(userRegist){
				loginListener.excuteHttpTask();
			//평소 디버그모드시 이것으로 실행할것.
//				Intent intent = new Intent(this, MainActivity.class);
//				startActivity(intent);
//				finish();
				
			} else {
				setUserInform();
			}
//			registerToken();
			break;
		}
		}

		return true;
	}
	
	public void setUserInform(){
		String userId = CafeNoaPreference.getUserID(this);
		if(userId==null || userId.equalsIgnoreCase("")){
			//preference에 저장된 userId가 없다면
			Intent intent = new Intent(this, LoginActivity.class);
			this.startActivity(intent);
		} else {
			Intent intent = new Intent(this, MainActivity.class);
			this.startActivity(intent);
		}
		finish();	
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		if (mHandler != null) {
			mHandler.removeMessages(1000);
			mHandler.removeMessages(2000);
		}

		if (thread != null && thread.isAlive()) {
			try {
				thread.join();
				thread.stop();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		am.restartPackage(getPackageName());

		super.onDestroy();
	}
	
	/**
	 * login할때 필요한 async task를 위한 리스너.
	 */
	AsyncTaskCompleteListener loginListener = new AsyncTaskCompleteListener(){

		@Override
		public void excuteHttpTask() {
			//Url 세팅.
			String url = Util.getUrl("MemberLogin");
			
			//id와 passwd 세팅해줌.
			String id = CafeNoaPreference.getUserID(mContext);
			String passwd = CafeNoaPreference.getUserPassword(mContext);
						
			//name value pair에 id와 password 세팅
			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("USER_ID", id));
			value.add(new BasicNameValuePair("USER_PASSWORD", passwd));
			value.add(new BasicNameValuePair("USER_GCM_ID", CafeNoaPreference.getGcmID(mContext)));
			//httpPostTast 실행.
			HttpPostTask http = new HttpPostTask(mContext, value, url, loginListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			//http 통신 실행후 서버로부터 오는 내용.
			//작업이 모두 완료되었다면.
			Log.v("result","reuslt :" + result);
			if(taskOk){
				int code = -1;
				String resultString = null;
				int point = 0;
				String userGrade = null;
				int dbVersion = -1;
				try {
					//코드 받아옴. JSON형태.
					//파싱하는 과정
					JSONObject object = new JSONObject(result);
					code = object.getInt("RESULT");
					resultString = object.getString("RESULT_STRING");
					point = object.getInt("USER_POINT");
					userGrade = object.getString("USER_GRADE");
					dbVersion = object.getInt("DB_VERSION");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				//코드가 내려오지 않은경우는 서버 에러 !
				if(code==-1){
					Log.v("CafeNoa","Server Error No code!");
					return;
				}
				
				if(code==Constants.NETWORK_SUCCESS){
					//저장된 db 버젼이 낮다면.
					if(dbVersion > Integer.valueOf(CafeNoaPreference.getDBVersion(mContext))){
						
						CafeNoaDBAdapter dbAdapter = new CafeNoaDBAdapter();
						dbAdapter.open(mContext);
						dbAdapter.removeMenuData();
						dbAdapter.Close();
						
						CafeNoaPreference.setRegistState(mContext, false);
//						CafeNoaPreference.setDBVersion(mContext, String.valueOf(dbVersion));
					}
					Log.v("CafeNoa","Save User Inform to Preference");
					
					Intent intent = new Intent(mContext, MainActivity.class);
					mContext.startActivity(intent);
					Toast.makeText(mContext, "성공적으로 로그인 되었습니다.", Toast.LENGTH_SHORT).show();

					finish();
				} else{ 
					if(code == Constants.ID_LOGIN_ERROR)
						Toast.makeText(mContext, "일치하는 아이디가 존재하지 않습니다.", Toast.LENGTH_SHORT).show();
					else if(code == Constants.PASSWORD_LOGIN_ERROR)
						 Toast.makeText(mContext, "일치하는 패스워드가 존재하지 않습니다.", Toast.LENGTH_SHORT).show();
				}
			}
		}
		
	};
}